/* eslint-disable array-callback-return,no-undef,guard-for-in */
import fetch from 'dva/fetch';
import React, { Component } from 'react';
import { Layout, Tabs, Form, Modal, Spin, message, Avatar } from 'antd';
import styles from '../../../index.less';
import Toolbar from '../../Common/ToolBar/ToolBar';
import TabMainTable from './TabMainTable';
import TabSubjectContent from './TabSubjectContent';
import TabExamine from './TabExamine';
import * as config from '../../../utils/config';
import * as commonFunc from '../../Common/commonFunc';
import baseHigher from '../../Common/baseHigher';
import PpopupPan from '../../../routes/ppopupPan/ppopupPan';
import CheckModel from '../../Common/CheckModel';
import imgCheck from '../../../assets/haveChecked.png';
import imgInvalid from '../../../assets/haveCancel.png';

const { confirm } = Modal;
const { Header, Content } = Layout;
const { TabPane } = Tabs;

class CahReceipt extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnData: config.btnData, /* 工具栏按钮 */
      masterConfig: { sId: '' }, // 主表 + 从表 配置
      sId: '', /* 业务数据ID */
      sActiveId: '', /* 窗体Id */
      disabled: false, /* 是否是查看状态 */
      loading: false,
      modalVisible: false, /* 弹窗显示状态 */
      modalPanel: {}, /* 弹窗面板属性 */
      mainTable: '', /* 主表 */
      tabSubjectContent: '', /* 主体内容 */
      tabExamine: '', /* 审核信息 */
      receiptData: { sBillType: 'customer' },
      subjectData: [],
      subjectDataSave: [],
      checkData: [],
      subjectDataTotal: {}, /* 列表数据汇总 */
      listRecordKey: { subjectDataKey: '', checkDataKey: '' }, /* 列表弹窗当前操作行,内部属性根据模块不同自定义 */
      gdsformconst: [], /* 常量 */
      visible: false, /* 审核不通过的弹窗 */
      sReturnMessage: [],
      sCheckModelId: '',
      sTabId: '', /* Tab页ID用于复制到等功能新弹出窗口避免弹出多个窗口 */
      newIdlength: 0, /* 复制到所用到的从表ID数 */
      newIdFlag: true, /* 页面复制数据后刷新渲染 */
      sListFormmasterId: '',
      sFormmasterId: '',
      configureMap: '',
      sFilterOrderBy: '',
      bFilter: '',
      currentData: [],
      pages: {},
      pageSize: '',
      iCountSum: '',
      formData: [],
      currentIndex: '',
      currentIndexFlag: false,
      btnDataAll: [],
      allTotalMoney: 0, /* 从表收款总金额 */
      allRoundingMoney: 0, /* 从表舍入总金额 */
      subjectDataOld: [], /* 从表老数据 */
      sBillType: '', /* 单据类型 */
      sCustomerId: '', /* 客户ID */
      sCustomerIdConfig: {}, /* 客户ID配置 */
      receiptDataOld: {}, /* 主表老数据 */
      receiptFlag: 0, /* 审核是否通过 */
      billnosetting: {}, /* 是否自动审核 */
      selectStatus: false,
      count: 0, /* 从表总行数 */
      report: [], /* 打印报表 */
    };
  }


  componentWillMount() {
    this.setState({
      selectStatus: true,
    });
  }

  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    const { gdsformconst, report } = nextProps;
    if (this.state.gdsformconst.length === 0) {
      this.setState({
        gdsformconst,
      });
    }
    if (this.state.report.length === 0) {
      const btnDataChild = [];
      report.forEach((child, i) => {
        btnDataChild.push({
          sName: `BtnPrint.${i}`,
          showName: child.sReportName,
          bVisible: true,
          sActiveId: '',
          sId: child.sId,
        });
      });
      this.setState({ btnDataChild, report });
    }
    const { billnosetting } = this.state;
    if (Object.keys(billnosetting).length === 0 && Object.keys(nextProps.billnosetting).length > 0) {
      this.setState({
        billnosetting,
      });
    }
    /* 配置 */
    const {
      sDataListTabId, urlData, formRoute, loading, sId, dataTotal, paneType, checkedId, disabled, sParentId, newIds, sFilterOrderBy, bFilter, pageSize, pages, sListFormmasterId, currentData, newkey,
    } = dataList;
    if (urlData !== undefined && Object.keys(urlData).length > 0 && paneType !== undefined && paneType !== '' && nextProps.sTabId === sParentId) {
      const paneKey = new Date().getTime().toString();
      const pane = {
        copyToData: dataList.copyToData, /* 复制到数据 */
        title: urlData.sMenuName,
        route: urlData.sName,
        formId: urlData.sId,
        checkedId,
        disabled,
        key: paneKey,
        sFilterOrderBy,
        bFilter,
        pageSize,
        pages,
        sListFormmasterId,
        currentData,
        newkey,
      };
      this.props.onAddPane(pane);
      return;
    }
    /* 数据Id */
    const { formId } = nextProps;
    /* 窗体全部配置 */
    const masterConfig = commonFunc.getWindowConfig('cahreceiptmaster', nextProps.formData);
    /* 弹出窗数据返回,渲染数据并关闭弹出框 */
    if ((nextProps.app.ppopupPane !== undefined &&
      nextProps.app.ppopupPane.mainConfig !== undefined) ? (nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key
      && nextProps.formRoute === nextProps.app.ppopupPane.mainConfig.route) : false) {
      const { resultValue } = nextProps.app.ppopupPane;
      const { modalType } = nextProps.app.ppopupPane;
      /* 通用弹窗数据返值处理 */
      if ((resultValue !== undefined) && modalType === 'ppopup') {
        /* 数据集名 */
        const { dataName } = nextProps.app.ppopupPane;
        /* 数据集类型，对象型为Map 数组型为List */
        const { dataType } = nextProps.app.ppopupPane;
        const data = this.state[`${dataName}`];
        if (dataType === 'Map') {
          const { sBillType } = this.state.receiptData;
          const sCustomerGuid = resultValue.sCustomerId.split('[-]')[0];
          if (sBillType === 'customer') {
            if (this.state.sCustomerId !== sCustomerGuid) {
              /* 调取从表数据 */
              const paramsMap = { sCustomerGuid };
              const value = {
                sProName: 'Sp_NotReceivables',
                paramsMap,
              };
              const { token } = this.props.app;
              const url = `${config.server_host}business/getProData?sModelsId=${formId}`;
              const options = {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  authorization: token,
                },
                body: JSON.stringify(value),
              };
              fetch(url, options).then(response => response.json()).then((json) => {
                if (json.code === 1) {
                  const { proData } = json.dataset.rows[0].dataSet;
                  if (proData !== null && proData[0] !== null && proData.length > 0) {
                    const { length } = proData;
                    /* 获取唯一Id */
                    const urlId = `${config.server_host}getUuid/${length}`;
                    const optionsId = {
                      method: 'GET',
                      headers: {
                        'Content-Type': 'application/json',
                        authorization: token,
                      },
                    };
                    fetch(urlId, optionsId).then(response => response.json()).then((datas) => {
                      const keys = datas.dataset.rows;
                      /* 从表赋值 */
                      const masterShowConfig = commonFunc.getConfigCondition(masterConfig.gdsconfigformslave, 'bVisible');
                      const subjectConfig = masterShowConfig.filter(item => item.sName === 'subjectData');
                      if (subjectConfig.length > 0 && subjectConfig[0].sAssignField !== '') {
                        const sAssignField = subjectConfig[0].sAssignField.split(',');
                        const subjectData = [];
                        proData.forEach((child, i) => {
                          const newData = {};
                          for (const childKey in child) {
                            const filterData = sAssignField.filter(item => item.split(':')[1] === childKey);
                            if (filterData.length > 0) {
                              filterData.forEach((fChild) => {
                                const fData = fChild.split(':');
                                const sName = fData[0];
                                const sValue = child[fData[1]];
                                newData[sName] = sValue;
                              });
                              newData.key = keys[i];
                              newData.handleType = 'add';
                            }
                          }
                          subjectData.push(newData);
                        });
                        const { receiptData } = this.state;
                        receiptData.dTotalMoney = 0;
                        receiptData.bAdvance = false;
                        receiptData.dAdvanceMoney = 0;
                        let allTotalMoney = 0;
                        let allRoundingMoney = 0;
                        subjectData.forEach((child) => {
                          if (child.dTotalMoney !== undefined) {
                            allTotalMoney += child.dTotalMoney * 1;
                          }
                          if (child.dRoundingMoney !== undefined) {
                            allRoundingMoney += child.dRoundingMoney * 1;
                          }
                        });
                        this.setState({
                          subjectData,
                          receiptData,
                          allTotalMoney,
                          allRoundingMoney,
                        });
                      }
                    });
                  } else {
                    const { receiptData } = this.state;
                    receiptData.dTotalMoney = 0;
                    receiptData.bAdvance = false;
                    receiptData.dAdvanceMoney = 0;
                    this.setState({
                      subjectData: [], receiptData, allTotalMoney: 0, allRoundingMoney: 0,
                    });
                  }
                } else {
                  message.error(json.msg);
                }
              });
            } else {
              this.setState({
                receiptData: this.state.receiptDataOld,
                subjectData: this.state.subjectDataOld,
              });
            }
          }
          for (const key of Object.keys(resultValue)) {
            if (key === 'sCustomerId') {
              const sCustomValue = resultValue[key];
              this.handleStore(sCustomValue, formId);
            }
            data[`${key}`] = resultValue[`${key}`];
          }
          if (this.state.sCustomerId !== sCustomerGuid) {
            this.setState({ [`${dataName}`]: data, modalVisible: false });
          } else {
            this.setState({ [`${dataName}`]: this.state.receiptDataOld });
          }
          this.setState({ modalVisible: false });
        } else if (dataType === 'List') {
          data.map((item) => {
            if ((item.sId === undefined ? item.key : item.sId) === this.state.listRecordKey[`${dataName}Key`]) {
              for (const key of Object.keys(resultValue)) {
                /* 赋值回带配置为#字段#,需取主表相应字段值 */
                if (typeof (resultValue[`${key}`]) === 'string' && resultValue[`${key}`].startsWith('#') && resultValue[`${key}`].endsWith('#')) {
                  item[`${key}`] = this.state.receiptData[`${key}`];
                } else {
                  item[`${key}`] = resultValue[`${key}`];
                }
              }
            }
            return item;
          });
          /* 弹窗数据回填后，清空listRecordKey 避免数据污染 */
          const subjectDataSave = this.handleSubjectDataSave(data);
          this.setState({
            [`${dataName}`]: data,
            modalVisible: false,
            subjectDataSave,
            listRecordKey: { subjectDataKey: '', checkDataKey: '' },
          });
        }
        /* 弹出框关闭 */
        this.props.onRemoveModalPane({});
        return;
      }
    }
    let { receiptData } = this.state;
    const outData = urlData !== undefined
      ? urlData.outData !== undefined
        ? urlData.outData : []
      : [];
    /* 到期应收 */
    if (outData.length > 0 && outData[0] !== null) {
      receiptData.dAccountReceivable = outData[0].dNoReceiptMoney;
      receiptData.dExpireReceivable = outData[0].dDueReceiptMoney;
      receiptData.bAdvance = true;
      this.setState({ receiptData });
    }
    if (nextProps.sTabId === sDataListTabId && nextProps.formRoute === formRoute && nextProps.formData.length > 0) {
      if (loading) {
        this.setState({ loading: true });
        return;
      }
      if (dataList.returnType !== undefined && dataList.returnType === 'CUD') {
        if (sId !== undefined && sId !== '') {
          this.setState({ sId });
        }
        this.setState({ disabled: dataList.disabled });
        this.handleRefresh(sId);
        return;
      }
      /* 窗体显示配置 */
      const masterShowConfig = commonFunc.getConfigCondition(masterConfig.gdsconfigformslave, 'bVisible');
      if (this.state.sActiveId === '') {
        const receiptPan = nextProps.app.currentPane;
        /* 获取工具栏, 主表，页签标题 */
        this.setState({ toolProps: nextProps });
        const { formData } = urlData;
        /* 窗体配置 */
        const mainTable = formData.filter(item => (item.sTbName.toLowerCase() === 'cahreceiptmaster'))[0];
        /* 匹配主表 */
        const mainConfig = mainTable.gdsconfigformslave;
        const tabSubjectContent = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabsubjectcontent'))[0];
        const tabExamine = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabexamine'))[0];
        /* 从表配置 */
        this.setState({
          formData,
          mainTable,
          disabled: receiptPan.disabled !== undefined ? receiptPan.disabled : false,
          sId: receiptPan.checkedId !== undefined ? receiptPan.checkedId : '',
          sActiveId: formId,
          tabSubjectContent: tabSubjectContent !== undefined ? tabSubjectContent : { showName: '主体内容', sId: new Date().getTime() + 1 }, /* 页签名 */
          tabExamine: tabExamine !== undefined ? tabExamine : { showName: '审核信息', sId: new Date().getTime() + 3 },
          sFilterOrderBy: receiptPan.sFilterOrderBy,
          bFilter: receiptPan.bFilter,
          currentData: receiptPan.currentData,
          sListFormmasterId: receiptPan.sListFormmasterId,
          pageSize: receiptPan.pageSize,
          pages: receiptPan.pages,
          currentIndex: receiptPan.newKey !== undefined ? receiptPan.newKey.split('-')[receiptPan.newKey.split('-').length - 1] : '',
        });
        if (receiptPan.copyToData !== undefined) {
          const copyToData = JSON.parse(JSON.stringify(receiptPan.copyToData));
          let masterData = { sBillType: 'customer' }; /* 主表数据 */
          let masterSlaveData = []; /* 第一个从表数据 */
          let newIdCount = 0;
          for (const value of Object.keys(copyToData)) {
            /* 是否数组 */
            if (!Array.isArray(copyToData[value])) {
              copyToData[value].sId = '';
              masterData = copyToData[value];
            } else {
              for (const v of copyToData[value]) {
                v.handleType = 'add';
                newIdCount += 1;
              }
              masterSlaveData = copyToData[value];
            }
          }
          this.setState({ receiptData: masterData, subjectData: masterSlaveData, newIdlength: newIdCount });
        }
        this.setState({ masterConfig, masterShowConfig });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data'
        && dataList.componentName.indexOf('cahreceiptslave') <= 0
        && dataList.componentName.indexOf('sysbillcheckresult') <= 0) {
        receiptData = Object.keys(urlData).length > 0
          ? urlData[0] : { sBillType: 'customer' };
        receiptData.tDueDate = receiptData.tDueDate === '0000-00-00 00:00:00' ? null : receiptData.tDueDate;
        const { bCheck } = receiptData;
        const sCustomValue = receiptData.sCustomerId;
        this.handleStore(sCustomValue, formId);
        let { selectStatus } = this.state;
        if (bCheck === true) {
          selectStatus = false;
        } else {
          selectStatus = true;
        }
        this.setState({
          selectStatus,
          receiptData,
          receiptDataOld: receiptData,
          loading: false,
          sTabId: nextProps.sTabId,
          sBillType: receiptData.sBillType,
          sCustomerId: receiptData.sCustomerId.split('[-]')[0],
        });
      } else if (newIds !== undefined && newIds.length > 0) {
        const { subjectData } = this.state;
        const ids = newIds;
        for (const v of subjectData) {
          [v.sId] = ids;
          ids.splice(0, 1);
        }
        this.setState({ subjectData, newIdlength: 0, newIdFlag: false });
      }
    }
    if (dataList.returnType !== undefined
      && dataList.returnType === 'data'
      && dataList.componentName === 'cahreceiptslave') {
      const subjectDataSave = Object.keys(urlData).length > 0
        ? urlData : [];
      let allTotalMoney = 0;
      let allRoundingMoney = 0;
      subjectDataSave.forEach((child) => {
        if (child.dTotalMoney !== undefined) {
          allTotalMoney += child.dTotalMoney * 1;
        }
        if (child.dRoundingMoney !== undefined) {
          allRoundingMoney += child.dRoundingMoney * 1;
        }
        const { sSrcType } = child;
        if (sSrcType === 'ReceiptInit' || sSrcType === 'Advance' || sSrcType === 'FinancialAdjust' || sSrcType === 'Payment') {
          const filterData = gdsformconst.filter(item => item.sName === sSrcType);
          child.sSrcType = filterData[0].showName;
        }
      });
      const { count } = this.state;
      if (subjectDataSave.length < count) {
        this.handleSpaceAdd(subjectDataSave, nextProps.formData);
      } else {
        this.setState({ subjectData: subjectDataSave });
      }
      this.setState({
        loading: false, subjectDataTotal: dataTotal[0], subjectDataOld: subjectDataSave, allTotalMoney, allRoundingMoney, subjectDataSave,
      });
    }
    if (dataList.returnType !== undefined
      && dataList.returnType === 'data'
      && dataList.componentName === 'sysbillcheckresult') {
      const checkData = Object.keys(urlData).length > 0
        ? urlData : [];
      this.setState({ checkData, loading: false });
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    let flag = true;
    /* 追加弹出框数值回填放行判断ppopupPane */
    if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
      && nextProps.app.ppopupPane.mainConfig !== undefined)
      ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
      if (nextState.disabled !== this.state.disabled) {
        return true;
      }
      flag = true;
    } else {
      flag = false;
    }
    return flag;
  }

  handleCount = (count) => {
    this.setState({ count });
  };

  handleSpaceAdd = (data, formData) => {
    const { count } = this.state;
    const subjectTable = formData.filter(item => (item.sTbName.toLowerCase() === 'cahreceiptslave'))[0];
    const subjectConfig = subjectTable.gdsconfigformslave;
    let totalRow = false;
    /* 取出汇总列 */
    subjectConfig.map((child) => {
      if (child.bSum) {
        totalRow = true;
      }
      return child;
    });
    const difCount = totalRow ? count - data.length - 1 : count - data.length;
    const { token } = this.props.app;
    const url = `${config.server_host}getUuid/${difCount}`;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    /* 获取表头 */
    const headerConfig = [];
    for (const child of subjectConfig) {
      if (child.sName !== '' && child.bVisible && child.showName !== '') {
        headerConfig.push({
          title: child.showName,
          dataIndex: child.sName,
          width: child.iFitWidth,
        });
      }
    }
    const newRow = [];
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const keys = json.dataset.rows;
        for (let i = 0; i < keys.length; i += 1) {
          const newData = {
            key: keys[i],
          };
          headerConfig.forEach((slaveChild) => {
            const ckey = slaveChild.dataIndex;
            const showConfig = subjectConfig.filter(item => (item.sName === ckey))[0];
            /* 新增一行的默认值添加进列表提交数据 */
            const columnValue = commonFunc.listDefaultValueNewAdd(showConfig, '');
            newData[ckey] = columnValue;
          });
          newRow.push({ ...newData, handleType: 'add' });
        }
        const subjectData = [...data, ...newRow];
        this.setState({ subjectData });
      }
    });
  };

  handleSubjectDataSave = (subjectData) => {
    /* 实际保存的数据 */
    const subjectDataSave = [];
    for (const child of subjectData) {
      let flag = 0;
      for (const key in child) {
        if (key !== 'key' && key !== 'handleType' && key !== 'sId' && key !== 'sParentId' && key.substring(0, 1) !== 'b') {
          if (child[key] !== '' && parseFloat(child[key] * 1) !== 0) {
            flag = 1;
            break;
          }
        }
      }
      if (flag === 1) {
        subjectDataSave.push(child);
      }
    }
    return subjectDataSave;
  };

  /* 应收款，到期应收处理 */
  handleStore = (sCustomValue, formId) => {
    const customersId = sCustomValue.split('[-]')[0];
    const myDate = new Date();
    const tStartDate = this.handleStartDate(myDate);
    const tEndDate = this.tEndDate(myDate);
    const paramsMap = {
      iType: '0',
      sStatistics: customersId,
      tStartDate,
      tEndDate,
    };
    const value = {
      sProName: 'Sp_Receivables_AR',
      paramsMap,
    };
    const storeUrl = `${config.server_host}business/getProData?sModelsId=${formId}`;
    const { dispatch } = this.props;
    dispatch({ type: 'content/getUrlPostData', payload: { url: storeUrl, value, returnType: 'data' } });
  };

  /* 当前日期的前一天 */
  handleStartDate = (myDate) => {
    const preDate = new Date(myDate.getTime() - (24 * 60 * 60 * 1000)); // 前一天
    const tStartDate = `${preDate.getFullYear()}-${preDate.getMonth() + 1}-${preDate.getDate()}`;
    return tStartDate;
  };

  /* 当前日期的后一天 */
  tEndDate = (myDate) => {
    const nextDate = new Date(myDate.getTime() + (24 * 60 * 60 * 1000)); // 前一天
    const tEndDate = `${nextDate.getFullYear()}-${nextDate.getMonth() + 1}-${nextDate.getDate()}`;
    return tEndDate;
  };

  /* 刷新 */
  handleRefresh = (newsId) => {
    const { dispatch } = this.props;
    const {
      masterConfig, sId, sActiveId, formData,
    } = this.state;
    let id = sId;
    if (newsId !== undefined && newsId !== '') {
      id = newsId;
    }
    if (id !== undefined && id !== '') {
      /* 表Id */
      const mainId = masterConfig.sId;
      /* 业务数据Id */
      const value = { sId: id };
      const sTabId = this.props.app.currentPane.key;
      /* 从表value */
      const slaveValue = {
        sSqlCondition: {
          sParentId: id,
        },
      };
      const subjectConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'cahreceiptslave'))[0];
      const checkConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'sysbillcheckresult'))[0];
      const subjectsId = subjectConfig.sId;
      const checksId = checkConfig.sId;
      const mainDataUrl =
        `${config.server_host}business/getBusinessDataByFormcustomId/${mainId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: mainDataUrl,
          sTabId,
          componentName: 'cahreceiptmaster',
          value,
          formRoute: '/cahreceiptmaster',
          returnType: 'data',
        },
      });
      const subjectDataUrl =
        `${config.server_host}business/getBusinessDataByFormcustomId/${subjectsId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: subjectDataUrl,
          sTabId,
          componentName: 'cahreceiptslave',
          value: slaveValue,
          formRoute: '/cahreceiptslave',
          returnType: 'data',
        },
      });
      const checkDataUrl =
        `${config.server_host}business/getBusinessDataByFormcustomId/${checksId}?sModelsId=${sActiveId}`;
      dispatch({
        type: 'content/getUrlPostData',
        payload: {
          url: checkDataUrl,
          sTabId,
          componentName: 'sysbillcheckresult',
          value: slaveValue,
          formRoute: '/sysbillcheckresult',
          returnType: 'data',
        },
      });
    } else {
      /* 应清空所有组件,或刷新不做任何处理或屏蔽刷新按钮 */
    }
  };

  handlePrintChild = (sId) => {
    const { formData } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    const sMainTableId = formData[0].sId;
    const queryFilter = {};
    formData.map((item) => {
      const sDataId = item.sId;
      queryFilter[sDataId] = sDataId === sMainTableId ? { sId: this.state.sId } : {
        sSqlCondition: {
          sParentId: this.state.sId,
        },
      };
    });
    const sReportId = sId;
    const queryFilterJson = escape(JSON.stringify(queryFilter));
    const urlPrint = `${config.server_host}printReport/printPdf/${sReportId}?queryFilter=${queryFilterJson}&sModelsId=${sActiveId}&sMaintableId=${sMainTableId}&token=${encodeURIComponent(token)}`;
    window.open(urlPrint);
  };

  /* 获取上一条下一条首条末条 */
  handleSearchData = (sValue) => {
    const { sActiveId } = this.state;
    const { token } = this.props.app;
    const {
      sListFormmasterId, sFilterOrderBy, bFilter, formData, pages, pageSize, currentIndex, currentIndexFlag,
    } = this.state;
    let currentIndexPop = currentIndexFlag ? currentIndex : ((pages.pageNum - 1) * pageSize) + Number.parseInt(currentIndex, 10);
    if (sValue === 'first') {
      currentIndexPop = 1;
    } else if (sValue === 'end') {
      currentIndexPop = pages.totalCount;
    }
    const url = `${config.server_host}business/getBusinessDataByIndex?sModelsId=${sActiveId}`;
    const arrayForm = {};
    formData.forEach((child) => {
      const keys = child.sId;
      arrayForm[`${keys}`] = keys;
    });
    const value = {
      sClientType: '1',
      sListFormmasterId,
      sFormmasterId: formData[0].sId,
      currentPosition: currentIndexPop,
      configureMap: arrayForm,
      sHandleType: sValue,
      iCountSum: pages.totalCount,
    };
    if (bFilter !== undefined && bFilter !== '' && Object.keys(bFilter).length > 0) {
      value.push({ bFilter });
    }
    if (sFilterOrderBy !== undefined && sFilterOrderBy !== '' && Object.keys(sFilterOrderBy).length > 0) {
      value.push({ sFilterOrderBy });
    }
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const values = json.dataset.rows[0];
        const currentPostion = values.currentPosition;
        formData.forEach((child) => {
          const sMainId = child.sId;
          const sMainTableName = child.sTbName;
          if (sMainTableName === 'cahreceiptmaster') {
            this.setState({
              receiptData: values[sMainId][0],
              sId: values[sMainId][0].sId,
            });
          } else if (sMainTableName === 'cahreceiptslave') {
            this.setState({
              subjectData: values[sMainId],
            });
          } else if (sMainTableName === 'sysbillcheckresult') {
            this.setState({
              checkData: values[sMainId],
            });
          }
        });
        this.setState({
          currentIndex: currentPostion,
          currentIndexFlag: true,
        });
      } else {
        message.error(json.msg);
      }
    });
  };
  /* 审核 */
  handleExamine = () => {
    const { sActiveId } = this.state;
    const { receiptData, subjectData, gdsformconst } = this.state;
    const sToVoid = gdsformconst.filter(item => (item.sName === 'sToVoid'));
    if (receiptData.bInvalid === true) {
      message.warning(sToVoid[0].showName);
      return;
    }
    const { token } = this.props.app;
    const url = `${config.server_host}business/doExamine?sModelsId=${sActiveId}`;
    const paramsMap = {
      iFlag: 1,
      iTmpCheck: 0,
      sFormGuid: sActiveId,
      sGuid: this.state.sId,
    };
    const value = {
      sClientType: '1',
      sProName: 'Sp_Calc_sRct',
      paramsMap,
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { outData } = json.dataset.rows[0].dataSet;
        if (outData[0] === undefined || outData[0] === null || outData[0] === '' || outData[0].sReturn.split('-').length < 2) {
          const checksReturnArray = outData[0].sReturn.split('-');
          if (checksReturnArray[0] !== undefined && checksReturnArray[0] !== '') {
            receiptData.bCheck = false;
            message.error(outData[0].sReturn);
          } else if (checksReturnArray[0] === undefined || checksReturnArray[0] === '') {
            receiptData.bCheck = true;
            message.success(json.msg);
            /* 刷新commList页面数据 */
            if (this.props.app.currentPane.refresh) {
              this.props.app.currentPane.refresh();
            }
          }
          this.setState({ receiptData, selectStatus: false });
        } else {
          const sReturnMessage = [];
          const sReturnArray = outData[0].sReturn.split('|');
          let sCheckModelId = '';
          if ((sReturnArray.length > 1) && ((sReturnArray[0].split('-')).length > 2)) {
            [sCheckModelId] = sReturnArray;
            [, sCheckModelId] = sCheckModelId.split('-');
          }
          sReturnArray.forEach((child) => {
            const smg = child.split('-');
            const sId = smg[0];
            const sData = subjectData.filter(item => (item.sId === sId));
            if (sData.length > 0) {
              const sNames = sData[0].sProductId.split('[-]');
              const sName = sNames.length > 2 ? sNames[1] : '';
              const messageCheck = `${sName}-${smg[2]}`;
              sReturnMessage.push(messageCheck);
              this.setState({
                sReturnMessage,
                sCheckModelId,
              });
            }
          });
          this.handleShowModal();
        }
      } else {
        message.error(json.msg);
      }
    });
  };

  /* 审核模板不通过时的弹窗 */
  handleShowModal = () => {
    this.setState({
      visible: true,
    });
  };
  /* 消审 */
  handleCancelExamine = () => {
    const { sActiveId } = this.state;
    const { receiptData } = this.state;
    const { token } = this.props.app;
    const url = `${config.server_host}business/doExamine?sModelsId=${sActiveId}`;
    const paramsMap = {
      iFlag: 0,
      iTmpCheck: 0,
      sFormGuid: sActiveId,
      sGuid: this.state.sId,
    };
    const value = {
      sClientType: '1',
      sProName: 'Sp_Calc_sRct',
      paramsMap,
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(value),
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const { outData } = json.dataset.rows[0].dataSet;
        if (outData[0] === undefined || outData[0] === null || outData[0] === '' || outData[0].sReturn.split('-').length < 2) {
          const checksReturnArray = outData[0].sReturn.split('-');
          if (checksReturnArray[0] !== undefined && checksReturnArray[0] !== '') {
            receiptData.bCheck = true;
            message.error(outData[0].sReturn);
          } else if (checksReturnArray[0] === undefined || checksReturnArray[0] === '') {
            receiptData.bCheck = false;
            message.success(json.msg);
            /* 刷新commList页面数据 */
            if (this.props.app.currentPane.refresh) {
              this.props.app.currentPane.refresh();
            }
          }
          this.setState({ receiptData, selectStatus: true });
        }
      } else {
        message.error(json.msg);
      }
    });
  };
  /* 新增 */
  handleAdd= () => {
    /* Tab标签Id */
    this.setState({
      selectStatus: true,
      receiptData: { sBillType: 'customer', bCheck: false, bInvalid: false },
      subjectData: [],
      subjectDataSave: [],
      checkData: [],
      disabled: false,
      sId: '',
    });
    const { formData } = this.state;
    this.handleSpaceAdd([], formData);
  };
  /* 修改 */
  handleEdit = (obj) => {
    const { disabled } = obj;
    const { receiptData, gdsformconst } = this.state;
    const sToVoidEdit = gdsformconst.filter(item => (item.sName === 'sToVoidEdit'));
    const sToExamineEdit = gdsformconst.filter(item => (item.sName === 'sToExamineEdit'));
    if (receiptData.bInvalid === true) {
      message.warning(sToVoidEdit[0].showName);
      return;
    }
    if (receiptData.bCheck === true) {
      message.warning(sToExamineEdit[0].showName);
      return;
    }
    this.setState({ disabled, selectStatus: true });
  };
  /* 删除 */
  handleDel = () => {
    const onhandleOk = this.handleOk;
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要删除?',
      onOk() {
        const value = {
          data: {
            sMasterTable: 'cahreceiptmaster',
            sId: [sId],
            sSlaveTable: [
              {
                tableName: 'cahreceiptslave',
                relationName: 'sParentId',
              }, {
                tableName: 'sysbillcheckresult',
                relationName: 'sBillId',
              }],
          },
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}business/delMasSlaBusinessData?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onhandleOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };

  handleInvalidOk = () => {
    const { receiptData } = this.state;
    receiptData.bInvalid = true;
    this.setState({
      receiptData,
    });
    /* 刷新commList页面数据 */
    if (this.props.app.currentPane.refresh) {
      this.props.app.currentPane.refresh();
    }
  };

  /* 作废 */
  handleInvalid = () => {
    const onInvalidOk = this.handleInvalidOk;
    const { receiptData, gdsformconst } = this.state;
    const sToExamineVoid = gdsformconst.filter(item => (item.sName === 'sToExamineVoid'));
    if (receiptData.bCheck === true) {
      message.warning(sToExamineVoid[0].showName);
      return;
    }
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要作废?',
      onOk() {
        const value = {
          sTableName: 'cahreceiptmaster',
          sId: [sId],
          sHandleType: 'toVoid',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}checkModel/updatebInvalid?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onInvalidOk();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };

  handleInvalidCancel = () => {
    const { receiptData } = this.state;
    receiptData.bInvalid = false;
    this.setState({
      receiptData,
    });
    /* 刷新commList页面数据 */
    if (this.props.app.currentPane.refresh) {
      this.props.app.currentPane.refresh();
    }
  };
  /* 取消作废 */
  handleCancelInvalid = () => {
    const onInvalidCancel = this.handleInvalidCancel;
    const { receiptData, gdsformconst } = this.state;
    const sToVoidExamine = gdsformconst.filter(item => (item.sName === 'sToVoidExamine'));
    if (receiptData.bCheck === true) {
      message.warning(sToVoidExamine[0].showName);
      return;
    }
    const { sId } = this.state;
    const { token } = this.props.app;
    const { sActiveId } = this.state;
    confirm({
      title: '确定要取消作废?',
      onOk() {
        const value = {
          sTableName: 'cahreceiptmaster',
          sId: [sId],
          sHandleType: 'cancel',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${config.server_host}checkModel/updatebInvalid?sModelsId=${sActiveId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            onInvalidCancel();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };
  /* 取消 */
  handleCancel =(type) => {
    const onhandleOk = this.handleOk;
    confirm({
      title: '确定要取消?',
      onOk() {
        onhandleOk(type);
      },
      onCancel() {},
    });
  };

  /* 非列表联动下拉 */
  handleSelectChange = (value, dataType, dataName) => {
    /* 数据集类型，对象型为Map 数组型为List */
    const data = this.state[`${dataName}`];
    if (dataType === 'Map') {
      for (const item of value) {
        data[`${item.key}`] = item.value;
      }
      this.setState({ [`${dataName}`]: data });
    }
  };

  /* 数据自动变更 */
  handleFormChange = (value) => {
    const { receiptData } = this.state;
    if (Object.keys(value)[0] === 'sBillType') {
      /* 单据类型不同，界面弹窗不同, 并且如不为客户，则清除主表除单据类型外的数据，并清除所有从表数据 */
      const { masterConfig } = this.state;
      const mainConfig = masterConfig.gdsconfigformslave;
      const sCustomerIdConfig = mainConfig.filter(item => (item.sName.toLowerCase() === 'scustomerid'))[0];
      sCustomerIdConfig.sAssignField = sCustomerIdConfig.sAssignField.replace(',sCustomerId:sId[-]sSupplyNo,sCustomerName:sSupplyName', '');
      sCustomerIdConfig.sAssignField = sCustomerIdConfig.sAssignField.replace(',sCustomerId:sId[-]sEmployeeNo,sCustomerName:sEmployeeName', '');
      sCustomerIdConfig.sAssignField = sCustomerIdConfig.sAssignField.replace(',sCustomerId:sId[-]sCustomerNo,sCustomerName:sCustomerName', '');
      sCustomerIdConfig.sSqlCondition = value;
      const receiptDataMaster = {
        ...receiptData,
        sBillType: value.sBillType,
        bAdvance: false,
        dAdvanceMoney: 0,
        sSalesId: '',
        dAccountReceivable: '',
        dExpireReceivable: '',
        dTotalMoney: '',
        sCustomerId: '',
        sCustomerName: '',
      };
      this.setState({ sCustomerIdConfig });
      this.setState({
        receiptData: receiptDataMaster,
        subjectData: [],
      });
      return;
    }
    if (Object.keys(value)[0] === 'sSettlementId') {
      if (value.sSettlementId !== 'bank') {
        receiptData.sBankId = '';
        receiptData.sBankAccount = '';
      }
    }
    /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
    const changeValue = commonFunc.changeValue(value);
    this.setState({
      receiptData: { ...receiptData, ...changeValue },
    });
  };
  /* 确认取消 */
  handleOk = () => {
    let lastIndex = -1;
    this.props.app.panes.forEach((pane, i) => {
      if (pane.key === this.props.app.currentPane.key) {
        lastIndex = i - 1;
      }
    });

    const panes = this.props.app.panes.filter(pane => pane.key !== this.props.app.currentPane.key);
    let currentPane;
    if (lastIndex >= 0) {
      currentPane = panes[lastIndex];
    } else if (lastIndex === -1 && panes.length > 0) {
      currentPane = panes[lastIndex + 1];
    } else {
      currentPane = { title: '', route: '', key: '0' };
    }
    this.props.onRemovePane(panes, currentPane);
    setTimeout(() => {
      /* 刷新commList页面数据 */
      if (this.props.app.currentPane.refresh) {
        this.props.app.currentPane.refresh();
      }
    });
  };
  /* 保存 */
  handleSubmit() {
    const { dispatch } = this.props;
    const { receiptData, gdsformconst, subjectData } = this.state;
    const sToExamineCheck = gdsformconst.filter(item => (item.sName === 'sToExamineCheck'));
    if (receiptData.bCheck === true) {
      message.warning(sToExamineCheck[0].showName);
      return;
    }
    /* 业务数据Id */
    const sTabId = this.props.app.currentPane.key;
    this.form.validateFieldsAndScroll((err, formValue) => {
      if (!err) {
        /* 判断总金额 = 收款总金额 + 预收款 */
        const { allTotalMoney } = this.state;
        const dTotalMoney = receiptData.dTotalMoney === undefined ? 0 : receiptData.dTotalMoney;
        const dAdvanceMoney = receiptData.dAdvanceMoney === undefined ? 0 : receiptData.dAdvanceMoney; /* 预收款 */
        if (dTotalMoney * 1 !== (allTotalMoney + dAdvanceMoney)) {
          const filterData = gdsformconst.filter(item => item.sName === 'receiptTotalMoney');
          message.warning(filterData[0].showName);
          return;
        }
        /* 从表保存，去除收款金额为空或为0的数据 */
        const saveSubjectData = [];
        subjectData.forEach((child) => {
          if (child.dTotalMoney !== undefined && parseFloat(child.dTotalMoney) !== 0) {
            child.sParentId = this.state.sId;
            saveSubjectData.push(child);
          }
        });
        let subjectDataSave = this.handleSubjectDataSave(saveSubjectData);
        const { checkData } = this.state;
        const stateFormValue = this.state.receiptData;
        const inputValue = { ...formValue, ...stateFormValue };
        inputValue.dAdvanceMoney = dAdvanceMoney; /* 预收款 */
        const { sActiveId } = this.state;
        const dataUrl = `${config.server_host}business/addUpdateDelBusinessData?sModelsId=${sActiveId}`;
        if (this.state.sId !== '') {
          if (this.state.sCustomerId !== inputValue.sCustomerId.split('[-]')[0]) {
            const delData = JSON.parse(JSON.stringify(this.state.subjectDataOld));
            delData.forEach((child) => {
              child.handleType = 'del';
            });
            subjectDataSave = [...subjectDataSave, ...delData];
          }
          inputValue.handleType = 'update';
          inputValue.sFormId = sActiveId;
          const value = {
            data: [{
              sTable: 'cahreceiptmaster',
              column: [inputValue],
            }, {
              sTable: 'cahreceiptslave',
              column: subjectDataSave,
            }, {
              sTable: 'sysbillcheckresult',
              column: checkData,
            }],
            sClientType: '1',
          };
          dispatch({
            type: 'content/getUrlPostData',
            payload: {
              url: dataUrl,
              sTabId,
              value,
              componentName: 'cahreceiptmaster',
              formRoute: '/cahreceiptmaster',
              returnType: 'CUD',
            },
          });
          setTimeout(() => {
            /* 刷新commList页面数据 */
            if (this.props.app.currentPane.refresh) {
              this.props.app.currentPane.refresh();
            }
          });
        } else {
          inputValue.handleType = 'add';
          const options = {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
          };
          const url = `${config.server_host}getUuid`;
          fetch(url, options).then(response => response.json()).then((json) => {
            if (json.code === 1) {
              const sId = json.dataset.rows[0];
              inputValue.sId = sId;
              inputValue.sFormId = sActiveId;
              /* 把新增时获取的唯一主键放在STATE中用于成功后刷新动作 */
              inputValue.maxBillNo = 'sBillNo';
              for (const item of subjectDataSave) {
                item.sParentId = sId;
              }
              for (const item of checkData) {
                item.sBillId = sId;
              }
              const value = {
                data: [{
                  sTable: 'cahreceiptmaster',
                  column: [inputValue],
                }, {
                  sTable: 'cahreceiptslave',
                  column: subjectDataSave,
                }, {
                  sTable: 'sysbillcheckresult',
                  column: checkData,
                }],
                sClientType: '1',
              };
              dispatch({
                type: 'content/getUrlPostData',
                payload: {
                  url: dataUrl,
                  sTabId,
                  value,
                  componentName: 'cahreceiptmaster',
                  formRoute: '/cahreceiptmaster',
                  returnType: 'CUD',
                  sId,
                },
              });
            }
          });
        }
      }
    });
  }
  /* 主体内容表单自动变更 */
  handleSubjectData = (value) => {
    const value2 = commonFunc.replaceSelectMasterData(value, this.state.receiptData);
    /* 收款金额与总金额一致 */
    let allTotalMoney = 0;
    let allRoundingMoney = 0;
    value2.forEach((child) => {
      if (child.dTotalMoney !== undefined) {
        allTotalMoney += child.dTotalMoney * 1;
      }
      if (child.dRoundingMoney !== undefined) {
        allRoundingMoney += child.dRoundingMoney * 1;
      }
    });
    const { receiptData } = this.state;
    const dAdvanceMoney = receiptData.dAdvanceMoney !== undefined ? receiptData.dAdvanceMoney : 0;
    receiptData.dTotalMoney = allTotalMoney + dAdvanceMoney;
    const subjectDataState = [...this.state.subjectData];
    const subjectDataDel = subjectDataState.filter(item => (item.handleType === 'del'));
    const subjectData = [...subjectDataDel, ...value2];
    for (const item of subjectData) {
      item.sParentId = this.state.sId;
    }
    const subjectDataSave = this.handleSubjectDataSave(subjectData);
    this.setState({
      subjectData,
      receiptData,
      allTotalMoney,
      allRoundingMoney,
      subjectDataSave,
    });
  };
  /* 审核表单自动变更 */
  handleCheckData = (value) => {
    const checkDataState = [...this.state.checkData];
    const checkDataDel = checkDataState.filter(item => (item.handleType === 'del'));
    const checkData = [...checkDataDel, ...value];
    for (const item of checkData) {
      item.sBillId = this.state.sId;
    }
    this.setState({
      checkData,
    });
  };

  handleForm = (form) => {
    this.form = form;
  };

  /* 弹窗关闭 */
  handlePpopUpPaneCancel = () => {
    /* 弹窗类型，下拉/弹窗 */
    const { modalType } = this.props.app.ppopupPane;
    /* 数据集名 */
    const { dataName } = this.props.app.ppopupPane;
    const data = this.state[`${dataName}`];
    /* 如果为下拉新增则下拉值重置为空 */
    if (modalType === 'select') {
      /* 数据集类型，对象型为Map 数组型为List */
      const { dataType } = this.props.app.ppopupPane;
      const { mainKey } = this.props.app.ppopupPane;
      /* 窗体关闭时下拉重置为空,避免下拉项停留在NEW选项 */
      if (dataType === 'Map' && data[`${mainKey}`] === '000') {
        data[`${mainKey}`] = ' ';
      } else if (dataType === 'List') {
        data.map((item) => {
          if (item.key === this.state.listRecordKey[`${dataName}Key`] && item[`${mainKey}`] === '000') {
            item[`${mainKey}`] = ' ';
          }
          return item;
        });
      }
    }
    /* 置空models中弹窗面板 */
    this.props.onRemoveModalPane({});
    /* 隐藏弹窗面板 */
    this.setState({
      modalVisible: false,
      [`${dataName}`]: data,
      listRecordKey: { subjectDataKey: '', checkDataKey: '' },
    });
  };

  /* 弹窗面板状态更改 */
  handleModalPane = (value) => {
    this.setState({ modalVisible: value.modalVisible, modalPanel: value });
  };

  /* 用于返回列表编辑框弹窗所属行主键 */
  handleRecordKey = (value) => {
    const { listRecordKey } = this.state;
    this.setState({ listRecordKey: { ...listRecordKey, ...value } });
  };

  /* 用于从表新增时判断主表必填字段是否填写 */
  handleSlaveAdd = () => {
    const { sCustomerId } = this.state.receiptData;
    if (sCustomerId === undefined) {
      const { masterShowConfig } = this.state;
      const { showName } = masterShowConfig.filter(item => (item.sName === 'sCustomerId'))[0];
      message.warning(`${showName}不能为空!`);
      return true;
    } else {
      return false;
    }
  };

  handleCopyTo = (activeId, value) => {
    const { receiptData, gdsformconst } = this.state;
    const sToVoidCopy = gdsformconst.filter(item => (item.sName === 'sToVoidCopy'));
    const sToCopyLimit = gdsformconst.filter(item => (item.sName === 'sToCopyLimit'));
    const sToCheckCopy = gdsformconst.filter(item => (item.sName === 'sToCheckCopy'));
    if (receiptData.bInvalid === true) {
      message.warning(sToVoidCopy[0].showName);
      return;
    }
    if (receiptData.bCopyLimit === true) {
      message.warning(sToCopyLimit[0].showName);
      return;
    }
    if (receiptData.bCheck === false) {
      message.warning(sToCheckCopy[0].showName);
      return;
    }
    const { dispatch } = this.props;
    const vConfig = value;
    /* 复制过去的主表数据 */
    let masterData = {};
    /* 复制过去的从表数据 */
    let masterSlaveData = [];
    if (vConfig.length > 0) {
      /* 过滤掉为了页面展示效果而存在的空数据 */
      const subjectData = this.state.subjectData.filter(item => (item.sId !== undefined && item.sId !== ''));
      const result = commonFunc.getBillCopyData(vConfig, this.state.receiptData, subjectData);
      if (result !== undefined) {
        ({ masterData } = result);
        ({ masterSlaveData } = result);
      }
    }
    /* Tab标签Id */
    const paneKey = new Date().getTime().toString();
    /* 窗体Id */
    const sActiveId = activeId;
    const sNameUrl = `${config.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlData',
      payload: {
        url: sNameUrl, sTabId: paneKey, urlDataType: 'newPane', disabled: false, sParentId: this.state.sTabId, copyToData: { masterData, masterSlaveData },
      },
    });
  };

  /* 判断是否是数字 */
  handleNum = (value) => {
    return value !== '' && !isNaN(value);
  };

  handleShare = () => {
    /* 分摊 */
    const { receiptData, subjectData } = this.state;
    const dTotalMoney = receiptData.dTotalMoney !== undefined ? receiptData.dTotalMoney : 0;
    let minusSum = 0; /* 负数求和 */
    let minusRoundingSum = 0; /* 负数舍入求和 */
    const minusData = []; /* 负数集 */
    let positiveSum = 0; /* 正数求和 */
    let positiveRoundingSum = 0; /* 正数舍入求和 */
    const positiveData = []; /* 正数集 */
    subjectData.forEach((child) => {
      child.dTotalMoney = 0;
      child.dRoundingMoney = this.handleNum(child.dRoundingMoney) ? child.dRoundingMoney : 0;
      if (child.dBalanceMoney < 0) {
        minusSum -= Math.abs(child.dBalanceMoney);
        minusRoundingSum -= Math.abs(child.dRoundingMoney);
        minusData.push(child);
      } else {
        positiveSum += child.dBalanceMoney;
        positiveRoundingSum += child.dRoundingMoney;
        positiveData.push(child);
      }
    });
    if (((minusSum - minusRoundingSum) + (positiveSum - positiveRoundingSum)) - dTotalMoney <= 0) {
      /* 够扣 */
      positiveSum -= minusRoundingSum;
      positiveSum -= positiveRoundingSum;
      positiveSum -= dTotalMoney; /* 去除分摊金额 */
      if (positiveSum >= 0) {
        for (let i = 0; i < minusData.length; i += 1) {
          /* 负数遍历 */
          const dBalanceMoney = Math.abs(minusData[i].dBalanceMoney); /* 余额正数 */
          const dRoundingMoney = minusData[i].dRoundingMoney !== undefined
            ? minusData[i].dRoundingMoney
            : 0;
          if (positiveSum <= dBalanceMoney) {
            minusData[i].dTotalMoney = -(positiveSum) - (dRoundingMoney * 1);
            if (minusData[i].handleType === undefined) {
              minusData[i].handleType = 'update';
            }
            break;
          } else {
            minusData[i].dTotalMoney = -(dBalanceMoney * 1) - (dRoundingMoney * 1);
            positiveSum -= dBalanceMoney - (dRoundingMoney * 1);
            if (minusData[i].handleType === undefined) {
              minusData[i].handleType = 'update';
            }
          }
        }
        for (let i = 0; i < positiveData.length; i += 1) {
          /* 正数遍历 */
          const { dBalanceMoney } = positiveData[i]; /* 余额正数 */
          const dRoundingMoney = positiveData[i].dRoundingMoney !== undefined
            ? positiveData[i].dRoundingMoney
            : 0;
          positiveData[i].dTotalMoney = (dBalanceMoney * 1) - (dRoundingMoney * 1);
          if (positiveData[i].handleType === undefined) {
            positiveData[i].handleType = 'update';
          }
        }
        receiptData.dAdvanceMoney = 0;
        receiptData.bAdvance = false;
      } else {
        /* 有预收 */
        for (let i = 0; i < positiveData.length; i += 1) {
          /* 正数遍历 */
          const { dBalanceMoney } = positiveData[i]; /* 余额正数 */
          const dRoundingMoney = positiveData[i].dRoundingMoney !== undefined
            ? positiveData[i].dRoundingMoney
            : 0;
          positiveData[i].dTotalMoney = (dBalanceMoney * 1) - (dRoundingMoney * 1);
          if (positiveData[i].handleType === undefined) {
            positiveData[i].handleType = 'update';
          }
        }
        for (let i = 0; i < minusData.length; i += 1) {
          /* 负数遍历 */
          minusData[i].dRoundingMoney = 0;
          if (minusData[i].handleType === undefined) {
            minusData[i].handleType = 'update';
          }
        }
        receiptData.dAdvanceMoney = Math.abs(positiveSum);
        receiptData.bAdvance = true;
      }
      this.setState({ receiptData, subjectData });
    } else if (((minusSum - minusRoundingSum) + (positiveSum - positiveRoundingSum)) - dTotalMoney > 0) {
      /* 不够扣情况 */
      minusSum -= minusRoundingSum;
      minusSum -= positiveRoundingSum;
      minusSum -= dTotalMoney; /* 去除分摊金额 */
      for (let i = 0; i < minusData.length; i += 1) {
        /* 负数遍历 */
        const dBalanceMoney = Math.abs(minusData[i].dBalanceMoney); /* 余额正数 */
        const dRoundingMoney = minusData[i].dRoundingMoney !== undefined
          ? minusData[i].dRoundingMoney
          : 0;
        minusData[i].dTotalMoney = -(dBalanceMoney * 1) - (dRoundingMoney * 1);
        if (minusData[i].handleType === undefined) {
          minusData[i].handleType = 'update';
        }
      }
      for (let i = 0; i < positiveData.length; i += 1) {
        /* 正数遍历 */
        const { dBalanceMoney } = positiveData[i]; /* 余额正数 */
        const dRoundingMoney = positiveData[i].dRoundingMoney !== undefined
          ? positiveData[i].dRoundingMoney
          : 0;
        if (Math.abs(minusSum) <= dBalanceMoney) {
          positiveData[i].dTotalMoney = Math.abs(minusSum) - (dRoundingMoney * 1);
          if (positiveData[i].handleType === undefined) {
            positiveData[i].handleType = 'update';
          }
          break;
        } else {
          positiveData[i].dTotalMoney = (dBalanceMoney * 1) - (dRoundingMoney * 1);
          minusSum = -(Math.abs(minusSum) - (dBalanceMoney * 1) - (dRoundingMoney * 1));
          if (positiveData[i].handleType === undefined) {
            positiveData[i].handleType = 'update';
          }
        }
      }
      receiptData.dAdvanceMoney = 0;
      receiptData.bAdvance = false;
      this.setState({ receiptData, subjectData });
    }
    let allTotalMoney = 0;
    let allRoundingMoney = 0;
    subjectData.forEach((child) => {
      if (child.dTotalMoney !== undefined) {
        allTotalMoney += child.dTotalMoney * 1;
      }
      if (child.dRoundingMoney !== undefined) {
        allRoundingMoney += child.dRoundingMoney * 1;
      }
    });
    this.setState({ allTotalMoney, allRoundingMoney });
  };

  render() {
    const { pageLoading } = this.props;
    const { props, state } = this;
    const { app } = props;
    const {
      visible, gdsformconst, sReturnMessage, sActiveId, sCheckModelId, receiptData,
    } = this.state;
    const { loading } = this.state;
    return (
      <div>
        <Spin spinning={loading}>
          {pageLoading ? '' :
          <div>
            <CahReceiptComponent
              {...props}
              {...state}
              handleSubmit={this.handleSubmit.bind(this)}
              handleEdit={this.handleEdit.bind(this)}
              handleAdd={this.handleAdd.bind(this)}
              handleCopyTo={this.handleCopyTo.bind(this)}
              handleOk={this.handleOk.bind(this)}
              handleCancel={this.handleCancel.bind(this)}
              handleRefresh={this.handleRefresh.bind(this)}
              handleDel={this.handleDel.bind(this)}
              onChange={this.handleFormChange.bind(this)}
              handleForm={this.handleForm.bind(this)}
              handleSubjectData={this.handleSubjectData.bind(this)}
              handleCheckData={this.handleCheckData.bind(this)}
              handleModalPane={this.handleModalPane.bind(this)}
              handleRecordKey={this.handleRecordKey.bind(this)}
              handleSelectChange={this.handleSelectChange.bind(this)}
              onSlaveAdd={this.handleSlaveAdd.bind(this)}
              onExamine={this.handleExamine.bind(this)}
              onCancelExamine={this.handleCancelExamine.bind(this)}
              onInvalid={this.handleInvalid.bind(this)}
              onCancelInvalid={this.handleCancelInvalid.bind(this)}
              onNext={this.handleSearchData.bind(this, 'next')}
              onPrior={this.handleSearchData.bind(this, 'up')}
              onFirst={this.handleSearchData.bind(this, 'first')}
              onLast={this.handleSearchData.bind(this, 'end')}
              onShare={this.handleShare}
              onPrintChild={this.handlePrintChild}
              onCount={this.handleCount}
              onModalClose={this.handlePpopUpPaneCancel}
            />
            <CheckModel
              visible={visible}
              gdsformconst={gdsformconst}
              sReturnMessage={sReturnMessage}
              app={app}
              sActiveId={sActiveId}
              sCheckModelId={sCheckModelId}
              sTbName="cahreceiptmaster"
              sBillKey="Sp_Calc_sRct"
              sBillNo={receiptData.sBillNo}
            />
            <Modal
              title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
              visible={this.state.modalVisible}
              onCancel={this.handlePpopUpPaneCancel.bind(this)}
              footer={null}
              width={1000}
              wrapClassName={styles.modal}
              destroyOnClose
            >
              <div className={styles.popupPan} id="popupPan">
                <PpopupPan handleGetResult={this.handleGetResult} />
              </div>
            </Modal>
          </div>}
        </Spin>
      </div>
    );
  }
}

const CahReceiptComponent = Form.create({
  mapPropsToFields(props) {
    const { receiptData, masterShowConfig } = props;
    const obj = commonFunc.mapPropsToFieldsChangeValue(masterShowConfig, receiptData, Form);
    return obj;
  },
  onValuesChange(props, changedFields) {
    props.onChange(changedFields);
  },
})((props) => {
  const { app, form } = props;
  const {
    sActiveId,
    masterConfig,
    sId,
    formData,
    dispatch,
    disabled,
    handleRefresh,
    handleEdit,
    handleCancel,
    handleSubmit,
    handleAdd,
    handleDel,
    changeDataFlag,
    handleModalPane,
    handleSelectChange,
    content,
    handleSubjectData,
    handleCheckData,
    handleRecordKey,
    subjectData,
    subjectDataTotal,
    checkData,
    listRecordKey,
    receiptData,
    onSlaveAdd,
    onInvalid,
    onCancelInvalid,
    onExamine,
    onCancelExamine,
    handleCopyTo,
    newIdlength,
    newIdFlag,
    onNext,
    onPrior,
    onFirst,
    onLast,
    gdsformconst,
    onShare,
    btnDataChild,
    onPrintChild,
    sCustomerIdConfig,
    billnosetting,
    subjectDataSave,
    onCount,
    selectStatus,
  } = props;
  /* 主表 */
  const { handleForm, onModalClose } = props;
  const onClose = onModalClose;
  const childProps = {
    app, form, sActiveId, sId, disabled, dispatch, content, masterConfig, handleModalPane, handleSelectChange, gdsformconst, onClose,
  };
  const { bInvalid, bCheck } = receiptData;
  const bShow = bInvalid || bCheck;
  let imgOption = '';
  if (bInvalid) {
    imgOption = <Avatar src={imgInvalid} />;
  } else if (bCheck) {
    imgOption = <Avatar src={imgCheck} />;
  }
  const mainProps = {
    formData,
    componentName: 'cahreceiptmaster',
    ...childProps,
    changeDataFlag,
    dataName: 'receiptData',
    dataType: 'Map',
    dataSet: receiptData,
    newIdlength,
    newIdFlag,
    onShare,
    sCustomerIdConfig,
    bCheck,
    billnosetting,
    subjectData,
    subjectDataSave,
  };
  /* 页签 */
  const { tabSubjectContent, tabExamine } = props;
  /* 主体内容表配置 refreshList用于弹窗数据回填后需要放行刷新动作 dataList列表数据下放 */
  const subjectConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'cahreceiptslave'))[0];
  const subjectProps = {
    formData,
    componentName: 'cahreceiptslave',
    ...childProps,
    handleRecordKey,
    handleSubjectData,
    masterConfig: subjectConfig !== undefined ? subjectConfig : { sId: '' },
    dataExist: subjectData.length > 0,
    dataName: 'subjectData',
    dataType: 'List',
    dataList: subjectData,
    refreshList: listRecordKey.subjectDataKey === '',
    dataTotal: subjectDataTotal,
    onSlaveAdd,
    onExamine,
    onCancelExamine,
    onNext,
    onPrior,
    onFirst,
    onLast,
    onPrintChild,
    subjectData,
    onCount,
  };
  /* 审核表配置 refreshList用于弹窗数据回填后需要放行刷新动作 dataList列表数据下放 */
  const checkConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'sysbillcheckresult'))[0];
  const checkProps = {
    formData,
    componentName: 'sysbillcheckresult',
    ...childProps,
    handleCheckData,
    handleRecordKey,
    masterConfig: checkConfig !== undefined ? checkConfig : { sId: '' },
    dataExist: Object.keys(checkData).length > 0,
    dataName: 'checkData',
    dataType: 'List',
    dataList: checkData,
    refreshList: listRecordKey.checkDataKey === '',
  };
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar
            componentName="toolreceipt"
            {...props}
            onAdd={handleAdd}
            onEdit={handleEdit}
            onBtnDel={handleDel}
            onBtnCancel={handleCancel}
            onRefresh={handleRefresh}
            onSubmit={handleSubmit}
            onBtnInvalid={onInvalid}
            onBtnCancelInvalid={onCancelInvalid}
            onBtnExamine={onExamine}
            onBtnCancelExamine={onCancelExamine}
            onCopyTo={handleCopyTo}
            onNext={onNext}
            onBtnPrior={onPrior}
            onBtnFirst={onFirst}
            onBtnLast={onLast}
            btnDataChild={btnDataChild}
            onBtnPrintChild={onPrintChild}
            bCheck={bCheck}
            selectStatus={selectStatus}
          >
            {handleForm(form)}
          </Toolbar>
        </Header>
        <Layout className={styles.clayout}>
          <Content className={styles.content}>
            <TabMainTable
              {...mainProps}
              onShare={onShare}
              onExamine={onExamine}
            />
            <div id="slaveTabs" className={bShow ? styles.bShow : ''}>
              <div style={{ display: bShow ? 'block' : 'none' }}>
                {imgOption}
              </div>
              <Tabs className={styles.slaveTabs}>
                <TabPane tab={tabSubjectContent.showName} key={tabSubjectContent !== '' ? tabSubjectContent.sId : 2} >
                  <TabSubjectContent {...subjectProps} />
                </TabPane>
                <TabPane tab={tabExamine.showName} key={tabExamine !== '' ? tabExamine.sId : 3} forceRender>
                  <TabExamine {...checkProps} />
                </TabPane>
              </Tabs>
            </div>
          </Content>
        </Layout>
      </Layout>
    </Form>
  );
});

export default baseHigher(CahReceipt);

